﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using NLBS.Data;
using NLBS.Entity;
using NLBS.Text;
using NLBS.Syndication;
using NLBS.Web;
using NLBS.Data.Business;
using NLBS.Framework;
using NLBS.Views;


namespace NLBS.Control
{
    public partial class article : BaseUserControl, IPostArticleView
    {
        private PostArticlePresenter _presenter;

        public PostArticlePresenter Presenter
        {
            get
            {
                if (this._presenter == null)
                    _presenter = new PostArticlePresenter();
                this._presenter.View = this;
                return _presenter;
            }
            
        }
        
        private void PresenterInit()
        {
            if (!this.IsPostBack)
            {
                this.Presenter.OnViewInitialized();
            }
            this.Presenter.OnViewLoaded();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            PresenterInit();
            PageInit();
           
        }

        private void PageInit()
        {
            //check login and post power
            if (!ShowArticleError()) return;
            //check eidt and delete power
            if (!IsPostBack)
            {
                checkAction();
                
            }
        }

        public ITagCollection<string, Tag> tagDic = TagData.GetTag();

        private bool ShowArticleError()
        {
            if (!string.IsNullOrEmpty(this.ErrorMsg))
            {
                ShowError(this.ErrorMsg);
                return false;
            }
            return true;
        }

        private void checkAction()
        {
            if (String.IsNullOrEmpty(act))
            {
                actionTxt.Text = "发表日志";
                author.Text = BlogInfo.CurrentUser.UserName;
                deletehref.Visible = false;
            }
            else
            {
                this.CheckActionError(null, null);
                if (!ShowArticleError()) return;
                if (currentArticle != null)
                {
                    BindEditArticle();
                }
            }
        }
        
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            //初始化日志
            this.InitArticle(null, null);
            //填充日志
            string oldTrackbackUrl = this.currentArticle.TrackbackURL;
            FillCommonForm();

            this.trackAgain = oldTrackbackUrl == this.currentArticle.TrackbackURL;
            //编辑日志
            if (act == "edit")
            {
                this.EditArticle(null, null);
                //发送日志引用
                Response.Redirect("/articleManage.aspx?act=update&id=" + this.currentArticle.ArticleID.ToString());
                return;
            }
            //新增日志
            this.PostArticle(null, null);
            Response.Redirect("articleManage.aspx?act=save");
            //发送日志引用
            //if (enableTrack)
            //{
            //    SendPing();
            //}

        }

        private void FillCommonForm()
        {
            Article article = currentArticle;
            article.CategoryID = Convert.ToInt32(CategoryDropDownList1.SelectedValue);
            article.Mode = Convert.ToInt32(log_mode.SelectedValue);
            article.Locked = RequestWrapper.GetCheckForm(log_locked);
            article.Title = RequestWrapper.GetFormString(log_title);
            article.Selected = RequestWrapper.GetCheckForm(log_selected);
            article.EditMark = string.Empty;
            article.UbbFlags = "html";
            article.IP = RequestWrapper.IP;
            article.IsTop = RequestWrapper.GetCheckForm(log_isTop);
            article.EnableInRss = RequestWrapper.GetCheckForm(log_enableRss);
            article.TrackbackURL = RequestWrapper.GetFormString(log_trackbackurl);
            //数据截断
            //article.Content1 = message.Html;
            //if (BlogInfo.EnableContentAutoSplit == 1)
            //{
            //    if (message.Text.Length > BlogInfo.ContentAutoSplitChars)
            //    {
            //        article.Content0 = HtmlHelper.SafeFormat(message.Text.Substring(BlogInfo.ContentAutoSplitChars));
            //    }
            //    else
            //    {
            //        article.Content0 = HtmlHelper.SafeFormat(message.Text);

            //    }
            //}
            //else
            //{
            //    article.Content0 = message.Html;
            //}
            article.Content0 =content0.Text;
            article.Content1 = richTextEditor.Text;
            FillTag();
        }

        private void FillTag()
        {
            string tagFrom = RequestWrapper.GetFormString(log_tag);
            if (!string.IsNullOrEmpty(tagFrom))
            {
                string[] tags = tagFrom.Split(new char[] { ',' });
                currentArticle.Tags.Clear();
                foreach (string tag in tags)
                {
                    if(!string.IsNullOrEmpty(tag.Trim().ToLowerInvariant()))
                    currentArticle.Tags.Add(tag.Trim().ToLowerInvariant());
                }
            }
        }

        private void BindEditArticle()
        {
            actionTxt.Text = "修改日志";
            deletehref.Visible = true;
            deletehref.HRef = Request.ApplicationPath + "articleManage.aspx?act=delete&id=" + articleID.ToString();
            author.Text = this.currentArticle.Author;
            CategoryDropDownList1.SelectedValue = this.currentArticle.CategoryID.ToString();
            log_mode.SelectedValue = this.currentArticle.Mode.ToString();
            log_locked.Checked = this.currentArticle.Locked;
            log_title.Value = this.currentArticle.Title;
            log_selected.Checked = this.currentArticle.Selected;
            log_isTop.Checked = this.currentArticle.IsTop;
            log_enableRss.Checked = this.currentArticle.EnableInRss;
            //log_enableComment.Checked = this.currentArticle.EnableComment;
            log_trackbackurl.Value = this.currentArticle.TrackbackURL;
            //message.Html = Article.Content1;
            content0.Text = this.currentArticle.Content0;
            richTextEditor.Text = this.currentArticle.Content1;
            log_tag.Value =string.Join(",",new List<string>(this.currentArticle.Tags).ToArray());
        }


        #region IPostArticleView Members
        private Article _currentArticle;
        public Article currentArticle
        {
            get
            {
                return _currentArticle;
            }
            set
            {
                _currentArticle=value;
            }
        }

        public string act
        {
            get { return RequestWrapper.GetQueryString("act"); }
        }

        public int articleID
        {
            get { return RequestWrapper.GetQueryInt("id"); }
        }

        private string _errorMsg;
        public string ErrorMsg
        {
            get
            {
                return _errorMsg;
            }
            set
            {
                _errorMsg=value;
            }
        }
        public event EventHandler PostArticle;

        public event EventHandler EditArticle;

        public event EventHandler DeleteArticle;

        public event EventHandler CheckActionError;

        public event EventHandler InitArticle;

        public bool enableTrackBack
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        private bool _trackAgain;
        public bool trackAgain
        {
            get
            {
                return _trackAgain;
            }
            set
            {
                _trackAgain = value;
            }
        }

        #endregion

        #region IErrorView Members

        public event CallError errorHandler;

        public void ShowErrorMsg(string error)
        {
            //error = this.ErrorMsg;
            ShowError(error);
        }

        private string _errormsg;
        public string errorMsg
        {
            get
            {
                return _errormsg;
            }
            set
            {
                _errormsg=value;
            }
        }

        public void ShowAjaxMsg(string error)
        {
            throw new NotImplementedException();
        }

        public string[] ErrorMsgs
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        #endregion
    }
}